import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import navigationSeevice from '../../../components/navigation/navigationSeevice';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const TAB_LIST = [
	{
		name: '可推送定向企业',
		status: 'push',
	},
	{
		name: '不可推送定向企业',
		status: 'unPush',
	},
]


export class OfferEnterpriseList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '企业列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props)
		this.tabIndex = 0;
		this.state = {
			status: 'data',
			listData: [],
			refreshIcon: false,
			recordCount: 0
		};
		this.reload = true
		this.totalPage = 0
		this.pageParams = Object.assign({}, props.navigation.state.params, { canSendCompany: true, pageNo: 1, pageSize: 10 });
		console.log(this.pageParams)
	}

	async componentWillMount() {
		this.initPage();
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let res = await HTTP.POST(API_GENERATE(API.TARGET_COMPANY), this.pageParams)
		if (res) {
			this.totalPage = res.totalPage;
			let responseData = res.rows;
			this.setState({
				status: responseData && responseData.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? responseData : this.state.listData.concat(responseData),
				refreshIcon: false,
				recordCount: res.recordCount
			})
			this.pageParams.pageNo = res.pageNo++;
		} else {
			this.setState({
				status: 'error'
			})
		}
	}
	// 刷新页面
	reloadPage() {
		this.reload = true;
		this.initPage();
	}
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}
	_onErrorRefresh = () => {
		this.initPage();
	}

	changeTab(index) {
		if (this.tabIndex === index) return;
		this.pageParams.pageNo = '1'
		this.tabIndex = index;
		this.setState({
			tabIndex: index
		})
		this.pageParams.canSendCompany = !index
		this.reloadPage();
	}
	// 搜索View
	_renderFilterWrap() {
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入企业名称"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchKey}
						onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
						onSubmitEditing={() => { this.reloadPage(); }}
					/>
				</View>
			</View>
		)
	}
	//tab View
	_renderTabWrap() {
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
								<Text style={[styles.tabText, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text>
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}


	_renderListItem = (data) => {
		let { resourceGroupNames, companyName, comments } = data.item
		return (
			<View style={styles.clickButtom}>
				<View>
					<Text style={[this.tabIndex ? { color: '#929292' } : { color: '#000' }, { fontSize: 14 * scale, fontWeight: '600' }]}>
						{companyName}</Text>
				</View>
				{resourceGroupNames ?
					<View style={{ marginTop: 10 * scale }}>
						<Text style={[this.tabIndex ? { color: '#929292' } : { color: '#000' }, { fontSize: 12 * scale }]} > 群组名称：{resourceGroupNames}</Text>
					</View>
					: null}
				{comments ?
					<View style={{ marginTop: 10 * scale }}>
						<Text style={[this.tabIndex ? { color: '#929292' } : { color: '#000' }, { fontSize: 12 * scale, lineHeight: 20 * scale }]}>不可选原因（{comments}）</Text></View>
					: null
				}
			</View>
		)
	}

	render() {
		let { status, listData, refreshIcon, recordCount } = this.state;
		return (
			<View style={styles.container}>
				{this._renderFilterWrap()}
				{this._renderTabWrap()}
				<View style={{ paddingHorizontal: 20 * scale, flex: 1, }}>
					<View style={{ marginTop: 10 * scale, alignItems: 'flex-end' }}>
						<Text>合计：{recordCount}家</Text>
					</View>
					{
						status == 'data' ? (<View style={{ flex: 1 }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.reloadPage() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
					}
					{
						status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this._onErrorRefresh} />) : null
					}
				</View>

			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
		paddingBottom: 30 * scale
	},
	filterWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 270 * scale,
		paddingLeft: 80 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 20 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 40 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'flex-start',
		paddingLeft: 18 * scale,
		paddingRight: 18 * scale,
	},
	tabText: {
		color: '#fff',
		textAlign: 'center'
	},
	tabCount: {
		marginTop: 4 * scale
	},
	tabItem: {
		paddingTop: 14 * scale,
		paddingBottom: 12 * scale,
	},
	listItem: {
		backgroundColor: '#fff',
		borderRadius: 4 * scale,
		marginBottom: 22 * scale
	},
	userInfo: {
		paddingLeft: 10 * scale,
		paddingRight: 10 * scale,
		paddingBottom: 6 * scale,
		paddingTop: 8 * scale,
		borderStyle: 'solid',
		borderTopColor: '#E3E7F0',
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
	},
	warningItem: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 13 * scale
	},
	userName: {
		fontSize: 12 * scale,
		marginBottom: 4 * scale,
		opacity: .8
	},
	tabTextWho: {
		paddingTop: 14 * scale
	},
	clickButtom: {
		backgroundColor: '#fff',
		borderRadius: 5 * scale,
		paddingHorizontal: 10 * scale,
		paddingVertical: 12 * scale,
		// flexDirection: 'row',
		// alignItems: 'center',
		marginTop: 10 * scale
	},

})